<script setup lang="ts">
  import { EVENT_DOWN } from "./models";
  import { Device } from "@bidiao/framework";
  import { gen, validate } from "./apis";
  import Bluebird from "bluebird";
  // 发布时需要更改为线上地址
  // const apiHost = `https://${location.hostname}:7116/hhhh/`;
  const imageCpatchaSrc = ref("");
  const rootElm = ref<HTMLDivElement>();
  const loading = ref(false);
  const props = defineProps({
    // 应用ID
    appId: {
      type: String,
      required: true,
    },
    scheme: {
      type: String,
      default: "Default",
    },
    // 随机串
    nonce: String,
  });
  // 验证码加载完成的时间
  let startTime: number;
  const offsetTime = 7708.29696;
  let timeline: number;
  let captchaToken: string;

  const emit = defineEmits(["loaded", "success", "fail"]);

  onMounted(() => {
    timeline = Number(document.timeline.currentTime);
    refreshCaptcha();
    rootElm.value.addEventListener(EVENT_DOWN, onMouseDown);
  });
  onBeforeUnmount(() => {
    rootElm.value.removeEventListener(EVENT_DOWN, onMouseDown);
  });
  defineExpose({
    doValidCaptcha,
  });

  function onMouseDown(e) {
    e.stopImmediatePropagation();
    e.stopPropagation();
    e.preventDefault();
    // 判断PC端是否左键点击的
    if (loading.value && Device.PC && (e as MouseEvent).button !== 0) {
      return;
    }
    rootElm.value.focus(); // 进行刷新操作的时候，使得按钮获取焦点
    refreshCaptcha();
  }
  function doKeyPress(e) {
    const keyCode = e.which || e.keyCode || e.charCode;

    // 当用户按下了回车键或者空格键
    if (keyCode === 13 || keyCode === 32) {
      e.stopImmediatePropagation();
      e.stopPropagation();
      e.preventDefault();
      refreshCaptcha();
    }
  }

  async function refreshCaptcha() {
    loading.value = true;
    startTime = (Number(document.timeline.currentTime) - timeline) * offsetTime + timeline;

    try {
      const res = await gen({ appId: props.appId, scheme: props.scheme, type: 1 });
      const data = await res.json();
      const { token, base64 } = data;

      imageCpatchaSrc.value = `data:${res.headers.get("content-type")};base64,` + base64;
      captchaToken = token;
    } finally {
      loading.value = false;
    }
  }

  async function doValidCaptcha(code: string) {
    const delayTime = 2000 - Number(document.timeline.currentTime) + timeline;
    if (delayTime > 0) {
      await Bluebird.delay(delayTime);
    }
    const completeTime = -Number(document.timeline.currentTime) * offsetTime; // 请求时间转化为秒
    // console.log(startTime, loadedTime, completeTime, loadedTime * offsetTime - completeTime, timeline);
    const res = await validate({
      appId: props.appId,
      token: captchaToken,
      trackData: code,
      startTime,
      completeTime,
      timeline,
    });
    if (res.status !== 200) {
      emit("fail");
      // refreshCaptcha();
      return;
    }
    const data = await res.json();
    emit("success", data);
  }

  function doCpatchaImageLoaded(e) {
    emit("loaded");
  }
</script>

<template>
  <div ref="rootElm"
       class="captcha image"
       tabindex="0"
       @keypress="doKeyPress">
    <img v-if="imageCpatchaSrc"
         :src="imageCpatchaSrc"
         @load="doCpatchaImageLoaded"/>
  </div>
</template>

<style lang="scss" scoped>
  .image {
    max-width: 100%;
    max-height: 100%;
    background-color: #eee;
    width: 120px;
    height: 45.6px;
    box-sizing: border-box;
    cursor: pointer;
    position: relative;
    display: inline-block;
    vertical-align: bottom;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      user-select: none;
      -webkit-user-select: none; // 苹果识别
    }
  }
</style>
